package cn.uyunsky.platform.config.reader;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.uyunsky.platform.BeanFactoryUtil;
import cn.uyunsky.platform.config.ConfigReader;
import cn.uyunsky.platform.config.bean.combobox.Combobox;
import cn.uyunsky.platform.config.bean.combobox.ComboboxsBean;
import cn.uyunsky.platform.config.bean.combobox.Entry;
import cn.uyunsky.platform.util.sql.SqlPlan;
import cn.uyunsky.platform.util.sql.SqlPlanFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;

import javax.sql.DataSource;

public class ComboxReader implements ConfigReader<ComboboxsBean> {

    private static Map<String, Combobox> comboboxs = new HashMap<String, Combobox>();

    @Override
    public void addBean(ComboboxsBean bean) {
        List<Combobox> list = bean.getCombobox();
        for (Combobox box : list) {
            if (box.isQuery()) {
                //查询数据库获取entry
                String sql = box.getSql();
                if (sql == null) {
                    throw new RuntimeException("Combobox[" + box + "]配置<sql>不能为空!!!");
                }
                DataSource dataSource = (DataSource) BeanFactoryUtil.getBean("dataSource");
                QueryRunner runner = new QueryRunner(dataSource);
                SqlPlan sqlplan = SqlPlanFactory.getInstance().getPlanCache(sql);
                try {
                    List<Object[]> qres = runner.query(sqlplan.getPlanSql(), new ArrayListHandler(), new Object[0]);
                    for (Object[] oAry : qres) {
                        Entry entry = new Entry();
                        entry.setKey(String.valueOf(oAry[0]));
                        entry.setValue(String.valueOf(oAry[1]));
                        box.addEntry(entry);
                    }
                } catch (SQLException e) {
                    throw new RuntimeException("执行sql:[" + sqlplan.getPlanSql() + "]异常", e);
                }
            }
            comboboxs.put(box.getId(), box);
        }
    }

    public String getSql(String id) {
        Combobox box = comboboxs.get(id);
        if (box != null && box.getSql() != null) {
            return box.getSql();
        } else {
            return null;
        }
    }

    public List<Entry> getEntrys(String id) {
        Combobox box = comboboxs.get(id);
        if (box != null && box.getEntry() != null) {
            return box.getEntry();
        } else {
            return null;
        }
    }

    /**
     * <p>Description: 是否查询combobox</p>
     * 参数说明:
     *
     * @return
     */
    public boolean isQuery(String id) {
        return comboboxs.get(id).isQuery();
    }
}
